import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import PermissionView from '@/views/PermissionView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      redirect: '/dashboard',
      children: [
        {
          path: '/dashboard',
          name: 'dashboard',
          component: () => import('../views/DashBoard.vue')
        },
        {
          path: '/user',
          name: 'user',
          children: [
            {
              path: 'list',
              name: 'userList',
              component: () => import('../views/user/UserList.vue')
            },
            {
              path: 'permission',
              name: 'permission',
              component: () => import('../views/user/Permission.vue')
            }
          ]
        },
        {
          path: '/permissions',
          name: 'permissions',
          component: PermissionView,
          meta: {
            requiresAuth: true,
            title: '权限管理'
          }
        }
      ]
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue'),
      meta: { requiresAuth: false }
    }
  ]
})

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  if (to.path === '/login') {
    if (token) {
      next('/')
    } else {
      next()
    }
  } else {
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router 